# -*- coding: utf-8 -*-



from django.shortcuts import render_to_response
from django.http import Http404
import datetime

from models import Post

from util.template import render_by_request_context


def main(request):
    
    posts = Post.objects.all()
    
    return render_by_request_context(request, 'blog/main.html', {'posts': posts })

def post(request, post_id=0, slug=''):
    
    try:
        if post_id:
            p = Post.objects.get(id=post_id)
        elif slug:
            p = Post.objects.get(slug=slug)
    except:
        raise Http404    
    #if posts:
    return render_to_response('blog/post.html', {'post': p, 'id': post_id, 'slug': slug})
    #else:
    #    raise Http404


def by_date(request, **kwargs):
    
    try:
        date = datetime.date(int(kwargs['year']),int(kwargs['month']),int(kwargs['day']))
    except ValueError:
        raise Http404('Неправильная дата')
    
    if kwargs['slug']:
        #try:
        p = Post.objects.filter(slug=kwargs['slug']).filter(date=date)
        
        #print p.query
        
        if p:
            p = p[0]
        #except:
        #    raise Http404('Нет такой записи за указанную дату')
        
        return render_to_response('blog/post.html', {'post': p, 'id': 0, 'slug': ''})
    
    else:
        posts = Post.objects.filter(date=date)
        
        if posts:
            return render_to_response('blog/main.html', {'posts': posts, 'in': 'main'})
    
    raise Http404()